<template>
  <div class="dashboard-container">
    <!-- 顶部导航 -->
    <el-header class="header">
      <div class="header-left">
        <div class="logo-section">
          <div class="logo-icon">📚</div>
          <h1>图书借阅管理系统</h1>
        </div>
      </div>
      <div class="header-right">
        <div class="user-info">
          <el-avatar :size="32" class="user-avatar">
            {{ user?.name?.charAt(0) }}
          </el-avatar>
          <span class="welcome-text">欢迎, {{ user?.name }}</span>
        </div>
        <el-button type="primary" plain @click="handleLogout" class="logout-btn">
          <el-icon><SwitchButton /></el-icon>
          退出登录
        </el-button>
      </div>
    </el-header>

    <!-- 主体内容区域 -->
    <div class="main-layout">
      <!-- 左侧控制面板 -->
      <div class="sidebar">
        <!-- 搜索和筛选区域 -->
        <el-card class="control-card modern-card" shadow="hover">
          <template #header>
            <div class="section-header">
              <div class="section-title">
                <el-icon class="section-icon"><Search /></el-icon>
                <span>数据筛选</span>
              </div>
            </div>
          </template>
          <div class="control-form">
            <div class="form-item">
              <label class="form-label">选择借阅者</label>
              <el-select v-model="searchForm.borrower" placeholder="请选择借阅者" clearable class="full-width">
                <el-option
                  v-for="borrower in borrowers"
                  :key="borrower"
                  :label="borrower"
                  :value="borrower"
                />
              </el-select>
            </div>
            <div class="form-item">
              <label class="form-label">借阅图书</label>
              <el-select v-model="searchForm.borrowed_book" placeholder="请选择图书" clearable class="full-width">
                <el-option
                  v-for="book in books"
                  :key="book"
                  :label="book"
                  :value="book"
                />
              </el-select>
            </div>
            <div class="form-item">
              <label class="form-label">借阅状态</label>
              <el-select v-model="searchForm.borrow_status" placeholder="请选择状态" clearable class="full-width">
                <el-option
                  v-for="status in borrowStatuses"
                  :key="status"
                  :label="status"
                  :value="status"
                />
              </el-select>
            </div>
            <div class="form-item">
              <label class="form-label">日期范围</label>
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                class="full-width date-picker"
              />
            </div>
            <div class="form-item">
              <div class="button-group">
                <el-button type="primary" @click="handleSearch" class="action-btn search-btn">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
                <el-button @click="resetSearch" class="action-btn reset-btn">
                  <el-icon><RefreshLeft /></el-icon>
                  重置
                </el-button>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 统计信息卡片 -->
        <el-card class="stats-card modern-card" shadow="hover" v-loading="statsLoading">
          <template #header>
            <div class="section-title">
              <el-icon class="section-icon"><Document /></el-icon>
              <span>数据统计</span>
            </div>
          </template>
          <div class="stats-content">
            <div class="stat-item">
              <div class="stat-number">{{ total }}</div>
              <div class="stat-label">总记录数</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ borrowers.length }}</div>
              <div class="stat-label">借阅者数量</div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧主内容区域 -->
      <div class="main-content">
        <!-- 数据表格 -->
        <el-card class="table-card modern-card" shadow="hover">
          <template #header>
            <div class="section-header">
              <div class="section-title">
                <el-icon class="section-icon"><Grid /></el-icon>
                <span>图书借阅管理系统</span>
              </div>
              <div class="header-stats">
                <el-tag type="primary" size="large" class="total-count">
                  <el-icon><Document /></el-icon>
                  共 {{ total }} 条记录
                </el-tag>
              </div>
            </div>
          </template>
          
          <div class="table-wrapper">
            <el-table
              :data="tableData"
              v-loading="loading"
              element-loading-text="正在加载数据..."
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.1)"
              border
              stripe
              style="width: 100%"
              :header-cell-style="{ 
                background: '#f8f9fa', 
                color: '#606266',
                fontWeight: 'bold',
                borderColor: '#e4e7ed'
              }"
              :row-style="{ height: '60px' }"
            >
              <el-table-column prop="borrow_date" label="借阅日期" width="180" sortable align="center">
                <template #default="{ row }">
                  <div class="date-cell">
                    <el-icon class="date-icon"><Calendar /></el-icon>
                    <span>{{ row.borrow_date }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="borrower" label="借阅者" width="150" align="center">
                <template #default="{ row }">
                  <el-tag type="info" size="large" class="borrower-tag">
                    <el-icon><User /></el-icon>
                    {{ row.borrower }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="borrowed_book" label="借阅图书" min-width="160" align="center">
                <template #default="{ row }">
                  <el-tag
                    type="primary"
                    size="large"
                    class="book-tag"
                  >
                    {{ row.borrowed_book }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="book_unit_price" label="图书单价" width="120" align="center">
                <template #default="{ row }">
                  <el-tag type="success" size="large" class="price-tag">
                    ¥{{ row.book_unit_price }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="borrow_status" label="借阅状态" width="120" align="center">
                <template #default="{ row }">
                  <el-tag 
                    :type="getStatusType(row.borrow_status)" 
                    size="large"
                    class="status-tag"
                  >
                    {{ row.borrow_status }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分页 -->
          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 15, 20]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              background
            />
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  RefreshLeft, 
  Grid, 
  Document, 
  Calendar,
  User,
  SwitchButton
} from '@element-plus/icons-vue'
import { user, logout } from '@/stores/auth'
import { 
  bookBorrowData, 
  borrowers, 
  books,
  borrowStatuses,
  loading as bookBorrowLoading,
  statsLoading,
  pagination,
  filters,
  fetchBookBorrowData,
  setFilters,
  clearFilters,
  setPagination,
  initBookBorrowData,
  fetchBorrowers,
  fetchBooks,
  fetchBorrowStatuses,
  fetchStats
} from '@/stores/bookBorrow'

const router = useRouter()

// 使用store中的状态
const loading = bookBorrowLoading
const currentPage = computed({
  get: () => pagination.value.page,
  set: (val) => setPagination(val)
})
const pageSize = computed({
  get: () => pagination.value.page_size,
  set: (val) => setPagination(pagination.value.page, val)
})
const total = computed(() => pagination.value.total)

// 搜索表单 - 绑定到store的filters
const searchForm = reactive({
  borrower: computed({
    get: () => filters.value.borrower,
    set: (val) => setFilters({ borrower: val })
  }),
  borrowed_book: computed({
    get: () => filters.value.borrowed_book,
    set: (val) => setFilters({ borrowed_book: val })
  }),
  borrow_status: computed({
    get: () => filters.value.borrow_status,
    set: (val) => setFilters({ borrow_status: val })
  }),
  dateRange: computed({
    get: () => {
      if (filters.value.start_date && filters.value.end_date) {
        return [filters.value.start_date, filters.value.end_date]
      }
      return []
    },
    set: (val) => {
      if (val && val.length === 2) {
        setFilters({ start_date: val[0], end_date: val[1] })
      } else {
        setFilters({ start_date: '', end_date: '' })
      }
    }
  })
})

// 表格数据直接使用store中的bookBorrowData
const tableData = computed(() => bookBorrowData.value)

// 状态类型
const getStatusType = (status) => {
  const types = {
    '已借出': 'warning',
    '已归还': 'success',
    '逾期': 'danger',
    '丢失': 'info'
  }
  return types[status] || 'primary'
}

// 搜索处理
const handleSearch = async () => {
  setPagination(1)
  await fetchBookBorrowData()
  ElMessage.success('搜索完成')
}

// 重置搜索
const resetSearch = async () => {
  clearFilters()
  await fetchBookBorrowData()
  ElMessage.info('搜索条件已重置')
}

// 分页处理
const handleSizeChange = async (val) => {
  setPagination(1, val)
  await fetchBookBorrowData()
}

const handleCurrentChange = async (val) => {
  setPagination(val)
  await fetchBookBorrowData()
}

// 退出登录
const handleLogout = () => {
  logout()
  router.push('/login')
  ElMessage.success('已退出登录')
}

onMounted(async () => {
  // 优化加载策略：先显示界面骨架，然后异步加载数据
  // 首先快速加载基础数据
  try {
    // 并行加载基础数据（借阅者列表、图书列表、借阅状态）
    await Promise.all([
      fetchBorrowers(),
      fetchBooks(),
      fetchBorrowStatuses()
    ])
    
    // 然后加载主要数据，使用非阻塞方式
    setTimeout(async () => {
      await fetchBookBorrowData()
    }, 100)
    
    // 最后加载统计数据
    setTimeout(async () => {
      await fetchStats()
    }, 200)
    
  } catch (error) {
    console.error('数据加载失败:', error)
    // 即使出错也要尝试加载基本数据
    await fetchBookBorrowData()
  }
})
</script>

<style scoped>
.dashboard-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
}

.dashboard-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="%23ffffff" opacity="0.1"/></pattern></defs><rect width="100%" height="100%" fill="url(%23grain)"/></svg>');
  pointer-events: none;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border: none;
  padding: 0 32px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  position: relative;
  z-index: 10;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  font-size: 32px;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-5px); }
}

.header-left h1 {
  margin: 0;
  background: linear-gradient(135deg, #409eff, #67c23a);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-size: 28px;
  font-weight: bold;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 16px;
  background: rgba(64, 158, 255, 0.1);
  border-radius: 20px;
  border: 1px solid rgba(64, 158, 255, 0.2);
}

.user-avatar {
  background: linear-gradient(135deg, #409eff, #67c23a);
  color: white;
  font-weight: bold;
}

.welcome-text {
  color: #606266;
  font-weight: 500;
}

.logout-btn {
  border-radius: 20px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.logout-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.main-layout {
  display: flex;
  padding: 24px;
  position: relative;
  z-index: 1;
}

.sidebar {
  width: 300px;
  padding-right: 24px;
}

.main-content {
  flex: 1;
}

.modern-card {
  border-radius: 16px;
  border: none;
  margin-bottom: 24px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.modern-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.section-icon {
  font-size: 20px;
  color: #409eff;
}

.control-card {
  margin-bottom: 20px;
}

.control-form {
  padding: 0;
}

.form-item {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  color: #606266;
  font-weight: 500;
  font-size: 14px;
}

.full-width {
  width: 100%;
}

.button-group {
  display: flex;
  gap: 12px;
  flex-direction: row;
}

.stats-card {
  margin-bottom: 20px;
}

.stats-content {
  display: flex;
  justify-content: space-around;
  text-align: center;
}

.stat-item {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.action-btn {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  flex: 1;
  padding: 12px 20px;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.search-btn {
  background: linear-gradient(135deg, #409eff, #66b1ff);
  border: none;
  color: white;
}

.search-btn:hover {
  background: linear-gradient(135deg, #66b1ff, #409eff);
}

.reset-btn {
  background: #f5f7fa;
  border: 1px solid #dcdfe6;
  color: #606266;
}

.reset-btn:hover {
  background: #ecf5ff;
  border-color: #409eff;
  color: #409eff;
}

.date-picker {
  border-radius: 8px;
}

/* 日期选择器响应式优化 */
:deep(.el-date-editor) {
  width: 100% !important;
}

:deep(.el-date-editor .el-range-separator) {
  flex-shrink: 0;
  padding: 0 5px;
}

:deep(.el-date-editor .el-range-input) {
  text-align: center;
}

.header-stats {
  display: flex;
  align-items: center;
}

.total-count {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  border-radius: 20px;
  font-weight: bold;
}

.table-wrapper {
  border-radius: 12px;
  overflow: hidden;
}

.table-card {
  height: fit-content;
}

.date-cell,
.metric-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  justify-content: center;
}

.date-icon,
.metric-icon {
  color: #909399;
}

.borrower-tag,
.book-tag,
.price-tag,
.status-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  border-radius: 16px;
  padding: 6px 12px;
  font-weight: bold;
}

.pagination-wrapper {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .sidebar {
    width: 280px;
  }
}

@media (max-width: 992px) {
  .main-layout {
    flex-direction: column;
    padding: 16px;
  }
  
  .sidebar {
    width: 100%;
    padding-right: 0;
    margin-bottom: 20px;
  }
  
  .button-group {
    flex-direction: row;
  }
}

@media (max-width: 768px) {
  .header {
    padding: 0 16px;
    flex-direction: column;
    gap: 16px;
    padding-top: 16px;
    padding-bottom: 16px;
  }
  
  .header-left h1 {
    font-size: 24px;
  }
  
  .main-layout {
    padding: 12px;
  }
  
  .button-group {
    flex-direction: column;
    gap: 8px;
  }
  
  .action-btn {
    width: 100%;
  }
  
  .stats-content {
    flex-direction: column;
    gap: 16px;
  }
  
  /* 移动端日期选择器优化 */
  :deep(.el-date-editor) {
    font-size: 14px;
  }
  
  :deep(.el-date-editor .el-range-input) {
    font-size: 12px;
    padding: 0 2px;
  }
  
  :deep(.el-date-editor .el-range-separator) {
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .main-layout {
    padding: 8px;
  }
  
  .control-card,
  .stats-card {
    margin-bottom: 16px;
  }
  
  /* 超小屏幕日期选择器优化 */
  :deep(.el-date-editor) {
    font-size: 13px;
    height: 36px;
  }
  
  :deep(.el-date-editor .el-range-input) {
    font-size: 11px;
    width: 80px;
  }
  
  :deep(.el-date-editor .el-range-separator) {
    font-size: 11px;
    padding: 0 3px;
  }
}

/* Element Plus 组件样式覆盖 */
:deep(.el-card__header) {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-card__body) {
  padding: 24px;
}

:deep(.el-table) {
  border-radius: 12px;
}

:deep(.el-table th) {
  background: #f8f9fa !important;
  border-color: #e4e7ed !important;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled)) {
  background-color: #f4f4f5;
  color: #606266;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled).is-active) {
  background-color: #409eff;
  color: #fff;
}
</style>